# -*- coding: utf-8 -*-
# @Date：2024/7/20 22:29:14
# @Author：CJiaの青姝
# @FileName：cj_auth
# @Editor：PyCharm2024
# @Remark：
from backend.settings import WHITE_LIST
from auths.models import Users, UsersRole, UsersToken
from system.models import RoleMenuItem, MenuButton
from ninja.security import HttpBearer

from utils.cj_jwt import decode_token

METHOD = {'GET': 1, 'POST': 2, 'PUT': 3, 'DELETE': 4, }


class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        # token解密
        payload = decode_token(token, UsersToken)
        if payload['code'] == 0:
            request_path = request.path  # 请求路径
            request_method = request.method  # 请求方法
            # 添加用户id
            request.user_id = payload['data']['id']
            if request_method == "GET":  # GET方法一律跳过
                return token
            # 判断是否在白名单中
            if request_path in WHITE_LIST:
                return token
            # 判断当前用户是否有操作权限
            role_ids = UsersRole.objects.filter(user_id=payload['data']['id']).values_list('role_id', flat=True)
            menu_button_ids = RoleMenuItem.objects.filter(role_id__in=role_ids).values_list('menu_button_id',
                                                                                            flat=True)
            permission = list(
                MenuButton.objects.filter(id__in=menu_button_ids).values_list("code", flat=True))
            # query_set = MenuButton.objects.filter(code__in=permission, api__regex=request_path,
            #                                       method=METHOD[request_method])
            query_set = MenuButton.objects.filter(code__in=permission, method=METHOD[request_method])
            if query_set.exists():
                request.user_id = payload['data']['id']
                return token
            else:
                raise TimeoutError(403, '演示环境，暂无操作权限')
        else:
            raise TimeoutError(401, payload['msg'])
